package demo.main;

import static net.sf.dynamicreports.report.builder.DynamicReports.cht;
import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.report;
import static net.sf.dynamicreports.report.builder.DynamicReports.stl;
import static net.sf.dynamicreports.report.builder.DynamicReports.type;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.builder.style.FontBuilder;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

public class ScatterChart extends MutiReport {

	@At("/getScatterChart")
	@Ok("json")
	public String getScatterChart(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("getScatterChart");
		build(request, response);
		// System.out.println("dddddddd : " + resultResult);
		return resultResult;
	}

	protected void build(HttpServletRequest request,
			HttpServletResponse response) {
		FontBuilder boldFont = stl.fontArialBold().setFontSize(12);

		TextColumnBuilder<Integer> xColumn = col.column("X", "x",
				type.integerType());
		TextColumnBuilder<Integer> y1Column = col.column("Y1", "y1",
				type.integerType());
		TextColumnBuilder<Integer> y2Column = col.column("Y2", "y2",
				type.integerType());

		try {
			reportBuilder = report()
					.setTemplate(Templates.reportTemplate)
					.columns(xColumn, y1Column, y2Column)
					.title(Templates.createTitleComponent(""))
					.summary(
							cht.scatterChart()
									//.setTitle("")
									.setTitleFont(boldFont)
									.setShowLines(false)
									.setXValue(xColumn)
									.series(cht.xySerie(y1Column),
											cht.xySerie(y2Column))
									.setXAxisFormat(
											cht.axisFormat().setLabel("X"))
									.setYAxisFormat(
											cht.axisFormat().setLabel("Y")))
					.pageFooter(Templates.footerComponent)
					.setDataSource(createDataSource());
			setResult(reportBuilder.toJasperPrint(), request, response);
		} catch (DRException e) {
			e.printStackTrace();
		}
	}

	private JRDataSource createDataSource() {
		DataSource dataSource = new DataSource("x", "y1", "y2");
		for (int i = -10; i < 10; i++) {
			dataSource.add(i, i + (int) (Math.random() * 5),
					i + (int) (Math.random() * 5));
		}
		return dataSource;
	}
}
